"""
@-*- coding: utf-8 -*-
@ python: 3.12.3
@ 创建者: JacksonCode
@ 创建时间: 2025-11-13
"""
import base64
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.backends import default_backend

def decrypt_by_private_key(data: str, key_pem: str) -> bytes:
    # 1. 解码 Base64 数据
    encrypted_data = base64.b64decode(data)

    # 2. 加载私钥（PKCS#8 格式，无密码）
    private_key = serialization.load_pem_private_key(
        key_pem.encode('utf-8'),
        password=None,
        backend=default_backend()
    )

    # 3. 使用私钥解密（通常使用 PKCS#1 v1.5 填充，除非特别指定 OAEP）
    try:
        decrypted = private_key.decrypt(
            encrypted_data,
            padding.PKCS1v15()  # 或者使用 padding.OAEP(...) 如果加密时用了 OAEP
        )
    except ValueError as e:
        raise Exception("解密失败，请确认填充方式或密钥是否正确") from e

    return decrypted

# 示例使用
key = """-----BEGIN PRIVATE KEY-----
MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIH4RbKot43WItT+
CfAadIJNZaZ6Tx15uC29mBgrVk8PhHzMTy6yt8g4fE+lnPz4i+MLSmwWPOpOEDei
uYIZUKR5n9kMOsHoPvrvWhzFFpZNhO2rgTXMPV7burBssm0fZACRG81uDH5apqlL
ql4cfVWiNtClsotoeI52d8/w9F5/AgMBAAECgYAxe81NkF8SaY0peu9dszTYx48E
K10j48vz3lOiIB3kTAwtV7xuEy1V1eu+h1eWGStpbksPjAf1TXNvO01V8z14VtBK
ltVqJEeuQjuEc5NiTOlLMP0t6yLzYtkrTc9uZI0sIn7CdZEao5KStdW5AK3/Mki4
3JrBLJEIIXbMGlesQQJBALaC++/5qVzqQwjf7gj0KbAZpHLj7qqovjb3jIuzQlt+
IXBuPzEh3A+Ui++rBC/IaCqU1KOb6gE6btPdVQ2exhsCQQC2TVtvzymEVexpC2Qt
PTQPeFXWch3CxaSbHMmvo9qI2Pp2gFyzZmekUVUA+A7sD3XgnF7wZ5TvOPyP+5pP
4l9tAkBnGTTySakXeKnncH/JhQurk8CmugVPWEUjTdGR9PBOOMDw/wYpXgQutO4b
tBKIX4AgVbSMu32Dtht3CPeL2x3zAkABvcdrz/zDiNaTQkqYrAb9Rtb7D2f9Xknu
OV4r0VLbD8eErkE0bXv789LuCXCLDLLBjHzTqwmfJ1oyPeMBdFYZAkBSMJ5vA8rR
KML8on1E3BCK/A30BuYHUH02Ll/o6QvXJympjPUG3V57tDkxLoXuxANqMJ9MBKuy
Ywj3sDyKqzyD
-----END PRIVATE KEY-----"""

# 注意：这里的 data 必须是 RSA 加密后、再 Base64 编码的字符串！
# 你给的 "$2a$04$..." 是 bcrypt，无法解密！这里仅作示例占位
# data = "$2a$04$.5XmnO2bk6UiaKzS2jCsQugqLMhwZylzA6YhIErEHkeEAad/Khp9q"
data = "ZZ1bF9WvQK+zAvObQqNhvIU3DtRI/uChiMz7NTtsGanw536soNRyWrI6QIm10hwt4xOb9c+FHjhgkcs/jSPrXnuYqMWWizURoMt/NzB3Oy3WAib6MrjekpqSBtunOAbvulzx+T/qvwNGKUIJFQjYTX+mANU2mazV5a77PR1SW6o="

try:
    decrypted_bytes = decrypt_by_private_key(data, key)
    print("Decrypted:", decrypted_bytes.decode('utf-8'))
except Exception as e:
    print("Error:", e)